<template>
  <!--  预约挂号-->
  <el-row style="height: 230px">
    <el-col :span="24">
      <h1>预约挂号</h1>
      <h1>请选择科室： </h1>
      <template v-for="dept in depts">
        <el-link @click="fetchDoctorList(dept.deptId)">{{ dept.deptName }}</el-link>
        |
      </template>
      <h1>请选择医生： </h1>
      <template v-for="doc in docs">
        <el-link @click="showDoctorDetailDialog(doc)">
          <el-tooltip
              class="box-item"
              effect="dark"
              :content="doc.docInt"
              placement="bottom"
          >
            {{ doc.docName }}
          </el-tooltip>
        </el-link>
        |
      </template>
    </el-col>
  </el-row>
  <!--  医生详情弹窗-->
  <el-dialog
      v-model="docDetailDialogVisible"
      title="医生详情"
      width="500"
  >
    <h1>医生姓名 : {{ doc.docName }}</h1>
    <h1>医生职称： {{ doc.docTitle }}</h1>
    <template v-for="dept in depts">
      <h1 v-if="dept.deptId == doc.deptId">医生科室： {{ dept.deptName }}</h1>
    </template>
    <h1>医生个人简介： {{ doc.docInt }}</h1>
    <h1>选择预约时间： </h1>
    <el-date-picker
        v-model="timeOfAppointment"
        type="datetime"
        placeholder="请选择日期时间"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="docDetailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="addRegistrationCheck">
          预约
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!--  我的挂号-->
  <el-row style="margin-top: 20px;height: 360px">
    <el-col :span="24">
      <el-divider/>
      <h1>我的挂号</h1>
    </el-col>
    <el-col :span="24">
      <template v-for="reg in regs">
        <el-card class="box-card" shadow="hover" style="margin-top: 10px">
          <template #header>
            <div class="card-header">
              <el-row :gutter="24">
                <el-col :span="20">
                  <p>
                    编码：<span>{{ reg.regUid }}</span>
                  </p>
                </el-col>
                <el-col :span="4">
                  <p>
                    挂号状态：
                    <el-tag type="danger" v-if="reg.regStatus == 1">未支付</el-tag>
                    <el-tag type="primary" v-else-if="reg.regStatus == 2">已支付</el-tag>
                    <el-tag type="success" v-else-if="reg.regStatus == 3">已就诊</el-tag>
                  </p>
                </el-col>
              </el-row>
            </div>
          </template>
          <p>
            患者：<span>{{ reg.patName }}</span>
          </p>
          <p>
            医生：<span>{{ reg.docName }}</span>
          </p>
          <p>
            预约时间：<span>{{ formatTime(reg.timeOfAppointment) }}</span>
            <el-button v-if="reg.regStatus != 3" type="text" @click="showUpdateDialog(reg)" style="margin-left: 10px">
              修改预约时间
            </el-button>
          </p>
          <template #footer>
            <el-button v-if="reg.regStatus == 1" type="primary" @click="goOp()">去缴费</el-button>
            <el-button v-if="reg.regStatus == 1" type="warning" @click="removeReg(reg)">取消预约</el-button>
            <el-button v-if="reg.regStatus == 2" type="success" @click="queueNumber(reg)">去排号</el-button>
          </template>
        </el-card>
      </template>
    </el-col>
  </el-row>
  <!--  修改预约时间-->
  <el-dialog v-model="regDialogFormVisible" title="修改挂号" width="500">
    <el-form :model="reg" label-width="auto">
      <el-form-item label="挂号编码">
        <el-input v-model="reg.regUid" disabled/>
      </el-form-item>
      <el-form-item label="患者">
        <el-input v-model="reg.patName" disabled/>
      </el-form-item>
      <el-form-item label="医生">
        <el-input v-model="reg.docName" disabled/>
      </el-form-item>
      <el-form-item label="挂号时间">
        <el-date-picker
            v-model="reg.timeOfAppointment"
            type="datetime"
            placeholder="请选择日期时间"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="regDialogFormVisible = false">取消</el-button>
      <el-button type="primary" @click="updateReg">修改</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {fetchDepartmentList} from "@/api/dept.js";
import {fetchDoctorList} from "@/api/doc.js";
import jsCookie from "jscookie";
import {addRegistration, fetchAllReg, removeReg, renewReg} from "@/api/reg.js";
import {ElMessageBox, ElNotification} from "element-plus";
import {fetchUser} from "@/api/pat.js";
import {addOp, removeOp} from "@/api/op.js";
import {addSn} from "@/api/sn.js";

export default {
  name: "reg",
  data() {
    return {
      depts: [],
      deptId: 0,
      docs: [],
      docDetailDialogVisible: false,
      doc: {},
      timeOfAppointment: "",
      reg: {},
      token: "",
      username: "",
      regs: [],
      regDialogFormVisible: false,
    }
  },
  created() {
    this.fetchDepartmentList();
    this.fetchDoctorList(1);
    this.token = jsCookie.get("token");
    this.fetchAllReg();
  },
  methods: {
    async updateReg() {
      try {
        if (this.reg.timeOfAppointment == "") {
          ElNotification({
            title: '错误！',
            message: "请选择预约时间！",
            type: 'warning',
          });
          return;
        }
        if (!this.isValidTime(new Date().toString())) {
          return;
        }
        await renewReg(this.token, this.reg).then(async (response) => {
          if (response.data.code == 200) {
            ElNotification({
              title: '成功！',
              message: "修改成功！",
              type: 'success',
            });
            this.regDialogFormVisible = false;
            this.fetchAllReg();
          } else {
            ElNotification({
              title: '失败！',
              message: response.data.msg,
              type: 'warning',
            });
          }
        })
      } catch (e) {
        ElNotification({
          title: '失败！',
          message: '出现未知问题，请联系管理员！',
          type: 'error',
        })
      }
    },
    showUpdateDialog(reg) {
      this.reg = {};
      this.reg.regId = reg.regId;
      this.reg.regUid = reg.regUid;
      this.reg.patId = reg.patId;
      this.reg.patName = reg.patName;
      this.reg.docId = reg.docId;
      this.reg.docName = reg.docName;
      this.reg.timeOfAppointment = reg.timeOfAppointment;
      this.regDialogFormVisible = true;
    },
    async queueNumber(reg) {
      // 获取今天的日期
      var today = new Date();
      // 提取reg.time中的日期部分，并转换为Date对象
      var regTime = new Date(reg.timeOfAppointment);
      // 检查时间的日期是否与今天相同
      if (regTime.getFullYear() === today.getFullYear() &&
          regTime.getMonth() === today.getMonth() &&
          regTime.getDate() === today.getDate()) {
        if (!this.isValidTime(reg.timeOfAppointment.toString())) {
          return;
        }
        let sn = {
          docId: reg.docId,
        };
        try {
          await addSn(this.token, sn).then(async (response) => {
            if (response.data.code == 200) {
              ElNotification({
                title: '成功！',
                message: "排号成功！",
                type: 'success',
              });
              reg.regStatus = 3;
              await renewReg(this.token, reg);
            } else if (response.data.code == 400) {
              ElNotification({
                title: '失败！',
                message: "出现未知问题，请联系管理员！",
                type: 'error',
              })
            }
          })
        } catch (e) {
          ElNotification({
            title: '失败！',
            message: "出现未知问题，请联系管理员！",
            type: 'error',
          })
        }
      } else {
        // 如果不是同一天，返回提示信息
        ElNotification({
          title: '失败！',
          message: "排号必须是挂号当天！",
          type: 'warning',
        })
      }
    },
    goOp() {
      this.$router.push('/patientHome/op');
    },
    async removeReg(reg) {
      try {
        const response = await removeReg(reg.regId);
        if (response.data.code == 200) {
          ElNotification({
            title: '成功！',
            message: "取消预约成功！",
            type: 'success',
          });
          await removeOp(reg.opId);
          this.fetchAllReg();
        } else if (response.data.code == 400) {
          ElNotification({
            title: '失败！',
            message: "出现未知问题，请联系管理员！",
            type: 'error',
          })
        }
      } catch (e) {
        ElNotification({
          title: '失败！',
          message: "出现未知问题，请联系管理员！",
          type: 'error',
        })
      }
    },
    async fetchAllReg() {
      const response = await fetchAllReg(this.token);
      this.regs = response.data.data;
    },
    isValidTime(timeStr) {
      // 尝试将时间字符串转换为 Date 对象
      const appointmentTime = new Date(timeStr);
      const now = new Date();
      if (appointmentTime < now) {
        // 预约时间小于当前时间
        this.errorMessage = "时间必须大于当前时间！";
        ElNotification({
          title: '错误！',
          message: this.errorMessage,
          type: 'warning',
        });
        return false;
      }
      const hours = appointmentTime.getHours();
      const minutes = appointmentTime.getMinutes();
      const seconds = appointmentTime.getSeconds();
      if (hours < 8 || hours > 17 || (hours === 17 && (minutes !== 0 || seconds !== 0))) {
        // 预约时间不在规定范围内
        this.errorMessage = "时间必须在8:00到17:00之间！";
        ElNotification({
          title: '错误！',
          message: this.errorMessage,
          type: 'warning',
        });
        this.timeOfAppointment = "";
        return false;
      }
      return true;
    },
    formatTime(timeStr) {
      const appointmentTime = new Date(timeStr);
      const year = appointmentTime.getFullYear();
      const month = String(appointmentTime.getMonth() + 1).padStart(2, '0');
      const day = String(appointmentTime.getDate()).padStart(2, '0');
      const hours = String(appointmentTime.getHours()).padStart(2, '0');
      const minutes = String(appointmentTime.getMinutes()).padStart(2, '0');
      return `${year}年${month}月${day}日 ${hours}时${minutes}分`;
    },
    addRegistrationCheck() {
      if (this.timeOfAppointment == "") {
        ElNotification({
          title: '错误！',
          message: "请选择预约时间！",
          type: 'warning',
        });
        return;
      }
      if (!this.isValidTime(this.timeOfAppointment.toString())) {
        return;
      }
      this.reg.docId = this.doc.docId;
      this.reg.timeOfAppointment = this.timeOfAppointment;
      this.reg.regUid = "REG" + new Date().getTime();
      this.fetchUsername();
      const formattedTime = this.formatTime(this.timeOfAppointment);
      ElMessageBox.confirm('请确认您的预约信息，患者姓名：' + this.username + '，医生姓名：' + this.doc.docName + '，预约时间：' + formattedTime, '友情提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.addRegistration();
      }).catch(() => {
        ElNotification({
          title: '失败！',
          message: "取消预约！",
          type: 'warning',
        });
      });
    },
    async fetchUsername() {
      const response = await fetchUser(this.token);
      this.username = response.data.data.patientName;
    },
    async addRegistration() {
      try {
        let op = {
          opDetail: '挂号',
          opMoney: 20,
          opDiscount: 0.8,
        };
        await addOp(this.token, op).then(async (res) => {
          this.reg.opId = res.data.data;
          const response = await addRegistration(this.token, this.reg);
          if (response.data.code == 200) {
            ElNotification({
              title: '成功！',
              message: "预约" + this.doc.docName + "成功！",
              type: 'success',
            });
            this.fetchAllReg();
            this.docDetailDialogVisible = false;
          } else if (response.data.code == 301) {
            ElNotification({
              title: '失败！',
              message: "请选择正确时间",
              type: 'warning',
            });
          } else if (response.data.code == 400) {
            ElNotification({
              title: '失败！',
              message: "出现未知问题，请联系管理员！",
              type: 'error',
            });
          }
        });
      } catch (e) {
        ElNotification({
          title: '失败！',
          message: "出现未知问题，请联系管理员！",
          type: 'error',
        });
      }
    },
    showDoctorDetailDialog(doc) {
      this.doc = {};
      this.doc = doc;
      this.timeOfAppointment = "";
      this.docDetailDialogVisible = true;
    },
    async fetchDoctorList(deptId) {
      this.deptId = deptId;
      const response = await fetchDoctorList(deptId);
      this.docs = response.data.data;
    },
    async fetchDepartmentList() {
      const response = await fetchDepartmentList();
      this.depts = response.data.data;
    }
  }
}
</script>

<style scoped>

</style>
